package com.study.talk.module.netty.handler;

import com.study.talk.common.util.SessionUtil;
import com.study.talk.module.entity.GroupInfo;
import com.study.talk.module.entity.GroupUserInfo;
import com.study.talk.module.entity.UserInfo;
import com.study.talk.module.netty.message.request.AcceptGroupRequest;
import com.study.talk.module.netty.message.response.AcceptGroupResponse;
import com.study.talk.module.netty.message.response.GroupMessageResponse;
import com.study.talk.module.service.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 对方同意加入群聊消息处理
 */

@Component
@Slf4j
@ChannelHandler.Sharable
public class AcceptGroupRequestHandler extends SimpleChannelInboundHandler<AcceptGroupRequest> {


    @Resource
    private GroupUserInfoService groupUserInfoService;

    @Resource
    private InviteGroupRecordService inviteGroupRecordService;

    @Resource
    private GroupInfoService groupInfoService;

    @Resource
    private UserService userService;

    @Resource
    private UserInfoService userInfoService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, AcceptGroupRequest msg) throws Exception {
        log.info("同意加入群聊事件,{}", msg);

        if (groupUserInfoService.queryHasMember(msg.getGroupId(),msg.getUserId())){ //用户已经在群里了,多个群成员邀请同一个用户加入群聊时会出现的情况
            return;
        }

        AcceptGroupResponse acceptGroupResponse = new AcceptGroupResponse();
        UserInfo userInfo = userInfoService.getById(msg.getUserId());
        acceptGroupResponse.setAcceptUserId(msg.getUserId());
        acceptGroupResponse.setDateTime(msg.getDateTime());
        acceptGroupResponse.setAcceptUserName(userInfo.getNickName());

        //默认没有同意入群
        acceptGroupResponse.setSuccess(false);

        //如果用户同意入群
        if (msg.getAccept()) {
            acceptGroupResponse.setSuccess(true);
            groupUserInfoService.addMember(msg.getGroupId(), msg.getUserId());
        }

        //删除邀请记录
        inviteGroupRecordService.removeInviteMember(msg.getGroupId(), msg.getInviteUserId(), msg.getUserId());
        acceptGroupResponse.setGroupId(msg.getGroupId());
        GroupInfo groupInfo = groupInfoService.getById(msg.getGroupId());
        acceptGroupResponse.setGroupName(groupInfo.getName());
        if (acceptGroupResponse.getSuccess()) {
            groupInfoService.sendAcceptJoinGroupMsg(groupInfo, userInfo);
        } else { //失败则通知邀请人
            userService.sendMessage(msg.getInviteUserId(), acceptGroupResponse);
        }

    }
}
